package ws

import (
	"fmt"
	"github.com/gorilla/websocket"
	"github.com/zeromicro/go-zero/core/threading"
	"net/http"
)

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func ServeWs(crs *ChatRoomServer, w http.ResponseWriter, r *http.Request) {
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		fmt.Println("Failed to upgrade connection to WebSocket:", err)
		return
	}
	client := Client{
		Conn:           *conn,
		ChatRoomServer: crs,
		Send:           make(chan Message),
	}

	threading.GoSafe(func() {
		client.readMessage(crs)
	})
	threading.GoSafe(func() {
		client.writeMessage(crs)
	})
}
